package com.atguigu.gmall.product.client;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

// 异步编排  CompletableFuture异步编排
public class test2 {
    public static void main(String[] args) {

       /* for (int j = 0; j < 10; j++) {
            //多线程之间是串行关系   这是开了3个线程
            CompletableFuture.runAsync(() -> {
                for (int i = 0; i < 3; i++) {
                    System.out.println("A");
                }
            }).thenAccept(t -> {
                for (int i = 0; i < 5; i++) {
                    System.out.println("B");
                }
            }).thenAccept(t -> {
                for (int i = 0; i < 10; i++) {
                    System.out.println("C");
                }
            });
        }*/

        //创建多线程
        /*CompletableFuture.runAsync(() -> {   runAsync没有返回值
            int i =1;
            i=2;
            i++;
            System.out.println(i);
        });
        CompletableFuture.supplyAsync(() -> {  supplyAsync有返回值
            int i = 1;
            i =2;
            i++;
            System.out.println(i);
            return i;
        });*/

        /*CompletableFuture.supplyAsync(() -> {
            int i =1;
            i=2;
            i++;
            //int j = 1/0;
            System.out.println("i:" +i);
            return i;
            //whenComplete使用的是上一个线程 然后继续使用
            // whenCompleteAsync使用的是等待上一个线程执行完 然后在线程池拿到一个新的线程
        }).whenCompleteAsync((t,u) -> {
            System.out.println("t=i :" + t);
            System.out.println("u:异常:" + u);
        });
*/
        //串行
        /*CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("串行1");
            return 123;
        }).thenApplyAsync((t) -> {
            System.out.println("t : " + t);
            return t;
        }).whenCompleteAsync((t,u) -> {
            System.out.println("whenCompleteAsync : t :" +t);
            System.out.println("whenCompleteAsync : u :" +u);
        }).join();*/

        //并行
        CompletableFuture<String> supplyAsync1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("并行1");
            return "123";
        });
        CompletableFuture<String> supplyAsync2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("并行2");
            return "456";
        });
        CompletableFuture<String> supplyAsync3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("并行3");
            return "789";
        });
        //等会  join  anyOf 等待一个  allOf等待全部
        CompletableFuture.allOf(supplyAsync1,supplyAsync2,supplyAsync3).join();

    }
}
